<template>
  <el-dialog :title="title" :visible.sync="visible" append-to-body>
    <div class="staff-component">
      <el-tabs v-model="activeName">
        <template v-if="calcTabsShow(1)">
          <el-tab-pane label="组织架构" name="1">
            <el-input v-model="userTreeFilterKey" clearable suffix-icon="el-icon-search" placeholder="关键词" />
            <div class="">
              <div>已选</div>
              <TagView :value="userTreeSelect" :option-list="userList" @close="handleTagChange" />
            </div>
            <el-tree
              ref="treeRef"
              :data="userTree"
              node-key="id"
              show-checkbox
              :default-checked-keys="userTreeSelect"
              :default-expanded-keys="userTreeSelect"
              :filter-node-method="handleTreeFilter"
              @check-change="handleTreeCheckChange"
            />
          </el-tab-pane>
        </template>
        <template v-if="calcTabsShow(2)">
          <el-tab-pane label="职务" name="2">
            职务
          </el-tab-pane>
        </template>
        <template v-if="calcTabsShow(3)">
          <el-tab-pane label="群组" name="3">
            <div class="group-block">
              <div class="search-box">
                <el-input v-model="groupFilterKey" clearable style="width: 300px;" suffix-icon="el-icon-search" />
                <el-button icon="el-icon-plus" type="primary" size="small" @click="handleGroupAdd">
                  新建群组
                </el-button>
              </div>
              <CheckBoxGroupView v-model="groupSelect" :option-list="groupListDataFilter" />
            </div>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>
    <div slot="footer" class="footer">
      <el-button size="mini" @click="handleClose">
        取消
      </el-button>
      <el-button size="mini" type="primary" @click="handleOk">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import CheckBoxGroupView from '@/components/CheckBoxGroupView'
import { getDeptUserTree } from '@/api/commonTree'
import TagView from './tag'
import { transTreeData } from '../../utils'
import { fetchDropGroupList } from '../../api/commonDropDown'
export default {
  name: 'StaffTemplateInput',
  components: { CheckBoxGroupView, TagView },
  props: {
    title: {
      type: String,
      default: ''
    },
    type: {
      type: Array,
      default: () => [1, 3]
    }
  },
  data() {
    return {
      activeName: '1',

      userTree: [], // 组织架构的用户树
      userList: [], // 组织架构的一维数据
      userTreeSelect: [], // 组织架构树的已选中的值
      userTreeFilterKey: '', // 组织架构树的过滤关键词

      groupListData: [], // 群组的集合
      groupSelect: [], // 群组中已选中的值
      groupFilterKey: '', // 群组 过滤的关键词

      visible: false
    }
  },
  computed: {
    groupListDataFilter: function() {
      const filter = this.$data.groupFilterKey
      return this.$data.groupListData.filter(e => e.value.indexOf(filter) > -1)
    }
  },
  watch: {
    userTreeFilterKey: function(val) {
      this.$refs.treeRef.filter(val)
    },
    type: {
      handler: function(val) {
        if (val.length > 0) {
          this.$data.activeName = val[0] + ''
        }
      },
      immediate: true
    }
  },
  methods: {
    open(val) {
      // val = { groupList: [], orgList: [] }
      //  val = [{notifyTargetType,notifyTargetDeptId, notifyTargetId}]
      // notifyTargetType 通知对象类别：1=人员 2=职务 3=群组id

      this.$data.visible = true
      this.setInitData(val)
      this.postGroupList()
      this.postDeptUserTree()
      return new Promise((resolve, reject) => {
        this.monitor = { resolve, reject }
      })
    },
    calcTabsShow(index) {
      return this.$props.type.includes(index)
    },

    // 设置初始值
    setInitData(data = {}) {
      this.$data.userTreeSelect = data.orgList || []
      this.$data.groupSelect = data.groupList || []
    },

    // 过滤掉人员为空的部门或机构
    filterEmptyDept(list) {
      const result = []
      const _map = {}
      const user = list.filter(e => e.type === 5)

      const findParent = (userList, doneList) => {
        const _result = []

        userList.forEach(user => {
          const userParent = list.find(e => e.id === user.parentDeptId)
          if (!_map[user.parentDeptId] && userParent) {
            _result.push(userParent)
            _map[user.parentDeptId] = true
          }
        })
        doneList.push(..._result)
        _result.length > 0 && findParent(_result, doneList)
      }

      findParent(user, result)

      return [...user, ...result]
    },

    // 获取提交值
    getSubmitData() {
      const result = {}
      if (this.calcTabsShow(1)) {
        const userTreeSelect = this.$refs.treeRef
          .getCheckedNodes()
          .filter(e => !e.children || e.children.length === 0)

        result.orgList = userTreeSelect
      } else {
        result.orgList = []
      }

      if (this.calcTabsShow(3)) {
        result.groupList = this.$data.groupSelect
      } else {
        result.groupList = []
      }
      return result
    },

    // 获取组织架构树
    postDeptUserTree() {
      getDeptUserTree({ deptType: 0, userType: 0 }).then(res => {
        this.$data.userList = this.filterEmptyDept(res)
        const userTree = transTreeData({
          list: this.$data.userList,
          rootId: '_0',
          appends: [{ in: 'name', out: 'label' }],
          props: { pidKey: 'parentDeptId' }
        })

        this.$data.userTree = userTree
      })
    },

    // 获取分组数据
    postGroupList() {
      fetchDropGroupList().then(res => {
        this.$data.groupListData = (res || []).map(e => ({ key: e.id, value: e.name }))
      })
    },

    // tree组件的过滤事件处理
    handleTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // tree 选中事件
    handleTreeCheckChange(a, b, c) {
      const userTreeSelect = this.$refs.treeRef
        .getCheckedNodes()
        .filter(e => !e.children || e.children.length === 0)
      this.$data.userTreeSelect = userTreeSelect
    },

    // 新增群组
    handleGroupAdd() {
      this.$emit('groupAdd')
    },

    handleTagChange(e) {
      this.$refs.treeRef.setChecked(e.id, false)
    },

    // 弹窗关闭事件
    handleClose() {
      this.$data.visible = false
      this.$emit('close')
    },

    // 弹窗保存事件
    handleOk() {
      const data = this.getSubmitData()
      this.monitor.resolve(data)
      this.handleClose()
    }
  }
}
</script>

<style lang="scss">
.staff-component {

  .group-block {
    .el-checkbox {
      display: block;
      margin: 20px 0;
    }

  }
}

</style>
